package com.tanhua.recommend.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.domain.mongo.VideoScore;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@RocketMQMessageListener(topic = "tanhua-video", consumerGroup = "tanhua-video-group")
@Slf4j
public class VideoScoreListener implements RocketMQListener<String> {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void onMessage(String message) {
        //1. 把消息转换为Map对象
        Map map = JSON.parseObject(message, Map.class);
        //2. 从Map中取出数据
        Long userId = Long.valueOf(map.get("userId").toString());
        String videoId = map.get("videoId").toString();
        Integer type = Integer.valueOf(map.get("type").toString());
        Long vid = Long.valueOf(map.get("vid").toString());

        //3. 创建VideScore对象，补全数据
        VideoScore vs = new VideoScore();

        vs.setUserId(userId);
        vs.setVideoId(vid);
        vs.setDate(System.currentTimeMillis());

        //4. 计算分数
        switch (type) {
            case 1: { //发布视频
                vs.setScore(2d);
                break;
            }
            case 2: { //视频点赞
                vs.setScore(5d);
                break;
            }
            case 3: { //取消点赞
                vs.setScore(-5d);
                break;
            }
            case 4: { //发布评论
                vs.setScore(10d);
                break;
            }
            default: {
                vs.setScore(0d);
                break;
            }
        }

        //5. 插入数据
        mongoTemplate.insert(vs);

    }
}
